//
//  EMMPhotoViewController.m
//  EMMApp
//
//  Created by Mac on 16/7/5.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMPhotoViewController.h"
#import "CollectionViewCell.h"
#import "PhotoViewController.h"
#import "FrameModel.h"
#import "DelProjectRealMapApi.h"
#import "SDPhotoBrowser.h"

@interface EMMPhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SDPhotoBrowserDelegate>
{
    UICollectionView *_collectionView;
    NSArray          *_bigUrlArray;
    NSMutableArray   *_frameArray;
    UIView           *_coverView;
    UIBarButtonItem *leftItemButton;
    NSInteger integer;
}
@property (nonatomic, strong) NSMutableArray *seleArr;
@property (nonatomic, strong) NSMutableArray *seleUrlArr;


@end

@implementation EMMPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    integer = 0;
    _seleArr = [[NSMutableArray alloc] init];
    _seleUrlArr = [[NSMutableArray alloc] init];
    [self creatNavigationController];
    [self loadSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)creatNavigationController {
    [self updateNavBar];
    [self configLeftBtn];
    self.title = @"浏览图片";
//    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more"] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    rightItme.tintColor = [UIColor colorFromHexCode:@"#ff7200"];
    
    if (_isYN == YES) {
        [self.navigationItem setRightBarButtonItem:rightItme];
    }else {
        
    }
}

- (void)rightClick:(UIButton *)btn {
    [self creat];
    [_collectionView reloadData];
}

- (void)creat {
    leftItemButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(btnLeftItemClick:)];
    leftItemButton.tintColor = [UIColor colorFromHexCode:@"#ff7200"];
    [self.navigationItem setLeftBarButtonItem:leftItemButton];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(btnRightItmeClick:)];
    rightItme.tintColor = [UIColor colorFromHexCode:@"#ff7200"];
    [self.navigationItem setRightBarButtonItem:rightItme];
    integer = 1;
    [_collectionView reloadData];
}

- (void)btnLeftItemClick:(UIButton *)btn {
    [leftItemButton setTitle:@""];
    [self creatNavigationController];
    integer = 0;
    [_collectionView reloadData];
}

- (void)btnRightItmeClick:(UIButton *)btn {
    if (_seleArr.count == 0) {
        [self showToast:@"请先勾选再确定"];
        return;
    }
    [leftItemButton setTitle:@""];
    [self creatNavigationController];
    integer = 0;
    if ([_tpye isEqualToString:@"1"]) {
        [_collectionView reloadData];
    }else {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (int i = 0; i < _seleArr.count; i++) {
            NSString *string = [_seleArr objectAtIndex:i];
            NSString *list = [_dataArrId objectAtIndex:[string intValue]];
            NSMutableDictionary *ditc = [[NSMutableDictionary alloc] init];
            [ditc setObject:list forKey:@"realMapId"];
            [arr addObject:ditc];
        }
        
        for (int i = 0; i < _seleUrlArr.count; i++) {
            NSString *string = [_seleUrlArr objectAtIndex:i];
            NSLog(@"______>>>>>>1 %@",string);
            NSLog(@"______>>>>>>2 %@",_dataArr);
            [_dataArr removeObject:string];
            NSLog(@"______>>>>>>2 %@",_dataArr);
            
        }
        
        [self postDelProjectRealMapApi:arr];
    }
}

#pragma mark - 新增图片
- (void)postDelProjectRealMapApi:(NSMutableArray *)realMapList {
    //    [self showHud:@"正在加载请稍等..."];
    DelProjectRealMapApi *api = [[DelProjectRealMapApi alloc] initWithRealMapList:realMapList];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        DelProjectRealMapApi *result = (DelProjectRealMapApi *)request;
        if (result.isSuccess) {
            [_seleArr removeAllObjects];
            [_collectionView reloadData];
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        [self hideHud];
        
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}


- (void)loadSubviews
{
    CGFloat width  = self.view.bounds.size.width;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((width-40)/3, (width-40)/3);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) collectionViewLayout:layout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.imgView.layer.borderWidth = 1;
    cell.imgView.layer.borderColor = [[UIColor colorFromHexCode:@"#CCCCCC"] CGColor];
    // 有时候SD会下载失败，需要添加这个
    [cell.imgView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    cell.imgView.contentMode =  UIViewContentModeScaleAspectFill;
    cell.imgView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    cell.imgView.clipsToBounds  = YES;
    [SDWebImageDownloader.sharedDownloader setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"fyuan_img"]];
    
    FrameModel *frame = [FrameModel getFrameWithView:cell];
    [_frameArray addObject:frame];

    if (integer == 1) {
        cell.imageBtn.hidden = NO;
        NSString *string = [NSString stringWithFormat:@"%ld",indexPath.row];
        if ([_seleArr containsObject:string]) {
            cell.imageBtn.image = [UIImage imageNamed:@"choose"];
        } else {
            cell.imageBtn.image = [UIImage imageNamed:@"choose_no"];
        }
    }else {
        cell.imageBtn.hidden = YES;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"--3 > %ld",indexPath.row);
    if (integer == 1) {
        NSString *string = [NSString stringWithFormat:@"%ld",indexPath.row];
        NSString *url = [_dataArr objectAtIndex:indexPath.row];
        if ([_seleArr containsObject:string]) {
            [_seleArr removeObject:string];
            [_seleUrlArr removeObject:url];
        } else {
            [_seleArr addObject:string];
            [_seleUrlArr addObject:url];
        }
         NSLog(@"--dasd > %@",_seleArr);
        [_collectionView reloadData];
    }else {
        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        photoBrowser.delegate = self;
        photoBrowser.currentImageIndex = indexPath.item;
        photoBrowser.imageCount = _dataArr.count;
        photoBrowser.sourceImagesContainerView = _collectionView;
        [photoBrowser show];
    }
   
}

// 返回临时占位图片（即原来的小图）
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
    CollectionViewCell *cell = (CollectionViewCell *)[self collectionView:_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    
    return cell.imgView.image;
    
}


// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    NSString *urlStr = [_dataArr objectAtIndex:index];
    return [NSURL URLWithString:urlStr];
}

@end
